import Aila
import DCloudUTSFoundation
import Foundation

@objc(UTSSDKModulesSnUtsAilaClient)
class AilaClient: NSObject, IAilaClient, AilaDeviceDelegate {

    private var ailaDevice: AilaDevice? = nil

    private var callback: SnUtsAilaCallback? = nil

    private func runOnUIThread(_ block: @escaping () -> Void) {
        DispatchQueue.main.async {
            block()
        }
    }

    private func sendEvent(_ event: String, data: Map<String, Any>?) {
        self.runOnUIThread { [weak self] in
            let result = SnUtsAilaResult()
            result.code = 0
            var d: [String: Any] = [
                "event": event
            ]
            if let data = data {
                d["data"] = data
            }
            result.data = UTSJSONObject(d)
            self?.callback?(result)
        }
    }

    func startService() {
        if self.ailaDevice == nil {
            let ailaDevice = AilaDevice.sharedInstance() as! AilaDevice
            ailaDevice.delegate = self
            self.ailaDevice = ailaDevice
        }
        self.ailaDevice?.start()
    }

    func onLightHandler(_ handler: @escaping SnUtsAilaCallback) {
        self.callback = handler
    }

    func configWifi(_ config: AilaConfig) {
        self.ailaDevice?.configWifi(config.ssid, password: config.pass, macAddr: config.mac)
    }

    func getBleList(_ callback: @escaping SnUtsAilaCallback) {
        if let list = self.ailaDevice?.getAilaConnectedDevices() as? NSMutableArray {
            var listData: [[String: Any]] = []
            list.forEach { item in
                if let item = item as? AilaPeripheral {
                    listData.append([
                        "name": item.localName,
                        "mac": item.macAddr,
                        "connected": false,
                    ])
                }
            }
            let result = SnUtsAilaResult()
            result.code = 0
            result.data = UTSJSONObject([
                "list": listData
            ])
            callback(result)
        }
    }

    func ailiDeviceConnect(_ state: AilaEventState) {
        sendEvent("ailiDeviceConnect", data: ["state": state.rawValue])
    }

    func ailaDeviceConfigWifiState(_ state: AilaEventState) {
        sendEvent("ailaDeviceConfigWifiState", data: ["state": state.rawValue])
    }

}

@objc(UTSSDKModulesSnUtsAilaHybrid)
@objcMembers
class Hybrid: NSObject {
    static let ailaClient = AilaClient()
}
